﻿using System;
using System.Configuration;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Windows.Forms;
using Google.GData.Client;
using Google.YouTube;
using Google.GData.Extensions.MediaRss;
using Google.GData.Client.ResumableUpload;

namespace iPhotoUploader.Library
{
    public class Youtube
    {
        protected string userName = ConfigurationManager.AppSettings["Youtube_UserName"];
        protected string password = ConfigurationManager.AppSettings["Youtube_Password"];
        protected string apiKey = ConfigurationManager.AppSettings["Youtube_APIKey"];
        private const string ApplicationName = "iPhotoUploader";
        private YouTubeRequest YouTubeRequest;
        private string AuthToken;
        private string UploadsUri = "http://gdata.youtube.com/feeds/api/users/{0}/uploads";

        public string LatestError { get; set; }

        public Youtube()
        {
            Authenticate(AuthToken);
        }

        public List<YouTubeVideo> GetUploadedVideos()
        {
            List<YouTubeVideo> uploadedVideos = new List<YouTubeVideo>();
            Uri uploads = new Uri(ProcessURI(UploadsUri));
            Feed<Video> videoFeed = YouTubeRequest.Get<Video>(uploads);

            videoFeed.Entries.ToList().ForEach(video => uploadedVideos.Add(
                new YouTubeVideo { VideoId = video.VideoId, 
                    Duration = video.Media.Duration.Seconds, 
                    ThumbNailUrl = video.Thumbnails[0].Url, 
                    Title = video.Title}));

            return uploadedVideos;
        }    

        private void Authenticate(string token)
        {
            YouTubeRequestSettings settings = new YouTubeRequestSettings(ApplicationName,
                    apiKey,
                    userName,
                    password);
            try
            {
                YouTubeRequest = new YouTubeRequest(settings);
                AuthToken = YouTubeRequest.Service.QueryClientLoginToken();
            }
            catch
            {
                LatestError = "There was a problem with your credentials";
                AuthToken = null;
            }

        }

        private string ProcessURI(string uri)
        {
            return string.Format(uri, userName);
        }
    }

    public class YouTubeVideo
    {
        protected string baseUrl = ConfigurationManager.AppSettings["Youtube_VideoUrl"];
        protected string seconds = string.Empty;

        public string VideoId { get; set; }
        public string Title { get; set; }
        public string ThumbNailUrl { get; set; }
        public Image ThumbNailImage
        {
            get
            {
                Stream str = null;
                HttpWebRequest wReq = (HttpWebRequest)WebRequest.Create(ThumbNailUrl);
                HttpWebResponse wRes = (HttpWebResponse)(wReq).GetResponse();
                str = wRes.GetResponseStream();

                return Image.FromStream(str);
            }
        }
        public string VideoUrl 
        {
            get { return string.Format(baseUrl, VideoId); }
        }
        public string Duration 
        {
            get
            {
                if (!string.IsNullOrEmpty(seconds))
                {
                    double secs = double.Parse(seconds);
                    TimeSpan t = TimeSpan.FromSeconds(secs);

                    return string.Format("{0:D2}:{1:D2}",
                                            t.Minutes,
                                            t.Seconds); 
                }
                return string.Empty;
            }
            set { seconds = value; } 
        }
    }
}
